#include "Joystick.h"

void Joystick::updatePos(float dt)
{
	mJsSprite->setPosition(mCurrentPoint);//ccpAdd(mJsSprite->getPosition(),ccpMult(ccpSub(mCurrentPoint, mJsSprite->getPosition()),0.5)));
}

void Joystick::setActive(bool active)
{
	mActive = active;
	if (active)
	{
		schedule(schedule_selector(Joystick::updatePos));
		CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0,false);
	}
	else
	{
		this->unschedule(schedule_selector(Joystick::updatePos));
		CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
	}
}

bool Joystick::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
	if (!mActive)
		return false;

	CCPoint touchPoint = touch->getLocation();

	if (ccpDistance(touchPoint, mCenterPoint) > mRadius)
		return false;
	mCurrentPoint = touchPoint;
	return true;
}

void  Joystick::ccTouchMoved(CCTouch* touch, CCEvent* event)
{
	CCPoint touchPoint = touch->getLocation();

	if (ccpDistance(touchPoint, mCenterPoint) > mRadius)
	{
		mCurrentPoint =ccpAdd(mCenterPoint,ccpMult(ccpNormalize(ccpSub(touchPoint, mCenterPoint)), mRadius));
	}else 
	{
		mCurrentPoint = touchPoint;
	}
}

void  Joystick::ccTouchEnded(CCTouch* touch, CCEvent* event)
{

	mCurrentPoint = mCenterPoint;
}

CCPoint Joystick::getDirection()
{
	return mCenterPoint.equals(mCurrentPoint)?CCPointMake(0,0):ccpNormalize(ccpSub(mCurrentPoint , mCenterPoint));
}

float Joystick::getVelocity()
{
	return ccpDistance(mCenterPoint, mCurrentPoint);
}

Joystick::Joystick():
	mJsSprite(NULL)
{

}

Joystick* Joystick:: create(CCPoint aPoint ,float aRadius ,CCSprite* aJsSprite,CCSprite* aJsBg){
	 Joystick *pRet=new Joystick;
	 if (pRet && pRet->init(aPoint,aRadius,aJsSprite,aJsBg))
	 {
		 pRet->autorelease();
		 return pRet;
	 }
	 else
	 {
		 CC_SAFE_DELETE(pRet);
		 return NULL;
	 }
}

Joystick* Joystick::init(CCPoint aPoint ,float aRadius ,CCSprite* aJsSprite,CCSprite* aJsBg)
{
	mActive = false;
	mRadius = aRadius;
	mCenterPoint = aPoint;
	mCurrentPoint = mCenterPoint;
	mJsSprite = aJsSprite;
	mJsSprite->setPosition(mCenterPoint);
	aJsBg->setPosition(mCenterPoint);
	this->addChild(aJsBg,0);
	this->addChild(mJsSprite,1);

	return this;
}
